package com.tyj.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.tyj.common.exception.NoStockException;
import com.tyj.gulimall.order.config.AlipayTemplate;
import com.tyj.gulimall.order.service.OrderService;
import com.tyj.gulimall.order.vo.confirmVo.OrderConfirmVo;
import com.tyj.gulimall.order.vo.confirmVo.OrderSubmitVo;
import com.tyj.gulimall.order.vo.confirmVo.SubmitOrderResponseVo;
import com.tyj.gulimall.order.vo.payVo.PayVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
@Slf4j
public class IndexController {

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;

    @RequestMapping("/{page}.html")
    public String page(@PathVariable("page") String page) {
        return page;
    }

    @RequestMapping("/toTrade")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("confirmVo", confirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo submitVo, Model model, RedirectAttributes attributes) {
        try {
            SubmitOrderResponseVo responseVo = orderService.submitOrder(submitVo);
            Integer code = responseVo.getCode();
            if (code == 0) {
                model.addAttribute("order",responseVo.getOrder());
                return "pay";
            } else {
                String msg = "下单失败;";
                switch (code) {
                    case 1:
                        msg += "防重令牌校验失败";
                        break;
                    case 2:
                        msg += "商品价格发生变化";
                        break;
                }
                attributes.addFlashAttribute("msg", msg);
                return "redirect:http://order.gulimall.com//toTrade";
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof NoStockException) {
                String msg = "下单失败，商品无库存";
                attributes.addFlashAttribute("msg", msg);
            }
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }

    /**
     * 支付宝会悄悄的给我们发送一个请求，告诉我们支付成功的信息 异步支付成功通知
     * @param orderSn
     * @return
     * @throws AlipayApiException
     */
    @ResponseBody
    @RequestMapping("/aliPayOrder")
    public String aliPayOrder(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getOrderPayInfo(orderSn);
        String pay = alipayTemplate.pay(payVo);
        System.out.println(pay);
        return pay;
    }


}
